package com.sdyeda.readiot.tools;

import java.util.Arrays;
import java.util.Calendar;

import com.sdyeda.readiot.iotinfo.IotData;

public class ReceiveBuff {

	byte[] buff = new byte[1024];

	private static final int receivesize = 60;
	private byte[] receive = new byte[receivesize];
	// 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F|
	// AA 75 命令 长 度 00 data----一般53字节
	// 10 1F|
	// ----
	// 20 3F|
	// ---- SUM
	// 30 31 32 33 34 35 36 37 38 39 40 4A|总计60字节
	private static final int datasize = 53;
	private byte[] data = new byte[datasize];
	

	private static byte[] head = { (byte) 0x55, 0x7A };

	// private Iotinfo iotinfo;
	private IotData iotdata = new IotData();

	public IotData getIotdata() {
		return iotdata;
	}

	public void setIotdata(IotData iotdata) {
		this.iotdata = iotdata;
	}

	private int readnums; // 读取字节数

	public int getReadnums() {
		return readnums;
	}

	public void setReadnums(int readnums) {
		this.readnums = readnums;
	}

	public ReceiveBuff() {
		clearbuff();
	}

	public boolean Analysis() {

		int seek = findHead();

		if (seek < 0) {
			return false;
		}
		//System.out.println(HexTools.bytesToHexString(buff, 0, buff.length));
		
		byte[] datalength = new byte[2]; 
		System.arraycopy(buff, seek+3, datalength, 0, 2);
		//System.out.println(HexTools.byte2ToInt(datalength));
		int length = HexTools.byte2ToInt(datalength);
		//System.out.println(length);

		receive = new byte[length+7];	//6个头字节+1个校验字节
		
		System.arraycopy(buff, seek, receive, 0, receive.length); // 固化，应从长度字节检验长度
		if (!checknum(receive)) {
			return false;
		}

		data = new byte[length];
		// 数据部分，53字节
		System.arraycopy(receive, 6, data, 0, length);

		//可根据类型——接受长度运行不同的解码程序。
		if(length == 53) {
			deCodeIotData();	
		}
		else if(length == 88) {		//一小时雨量计
			deCodeIotDataRain();
		}
		else if(length == 184) {	//10分钟雨量计
			deCodeIotDataRain2();
		}
		//其他直接返回
		return true;
	}

	//通用传感器
	// 00 01 02 03 04 05 06 07 0byte[] MakeReadBuffer(String id);8 09 0A 0B 0C 0D 0E 0F|
	// 传感器编号8字节           |BCD时间6字节    |温度*0.1|
	// 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F|
	// 测量值-偏移值-应变频-补偿频-|单位 4字节|类型|自编号16字节
	// 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F|
	// --------------------------------------|型号8字节
	// 30 31 32 33 34|总计53字节
	// --------------|
	void deCodeIotData() {
		// id
		iotdata.setSuccess(true);
		
		iotdata.setIotid(HexTools.bytesToHexString(data, 0, 8));

		// 时间
		byte[] bcdtime = new byte[6];
		System.arraycopy(data, 8, bcdtime, 0, 6);
		iotdata.setTime(HexTools.BytesBCDtoDate(bcdtime));

		iotdata.setTemp(deCodeInt(14) * 0.1); 	// 温度
		iotdata.setValue(deCodeInt(16)); 		// 测量值--原值
		iotdata.setOffset(deCodeInt(18));		// 偏移值--原值
		iotdata.setStrain(deCodeInt(20) * 0.1); // 应变频率
		iotdata.setCompen(deCodeInt(22) * 0.1); // 补偿频率

		// 单位-字符串
		byte[] strunit = new byte[4];
		System.arraycopy(data, 24, strunit, 0, 4);

		// 自编号-字符串？
		byte[] strid = new byte[16];
		System.arraycopy(data, 29, strid, 0, 16);

		// 设备类型-字符串
		byte[] strtype = new byte[8];
		System.arraycopy(data, 45, strtype, 0, 8);

		try {
			iotdata.setUnit(new String(strunit, "GB2312").trim());
			iotdata.setSid(new String(strid, "GB2312"));
			iotdata.setStype(new String(strtype, "GB2312").trim());
		} catch (Exception e) {

		}
	}

	//1小时雨量计
	// 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F|
	// 传感器编号8字节           |自编号-16字节            |
	// 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F|
	//                        |型号8字节                |
	// 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F|
	// 年 月  日 00 00 00 |雨量数据48字节      每小时2字节 |
	// 30 31 32 33 34....
	// --------------|
	void deCodeIotDataRain() {
		// id
		System.out.println("1小时雨量计："+HexTools.bytesToHex(receive));
		
		iotdata.setSuccess(true);
		
		iotdata.setIotid(HexTools.bytesToHexString(data, 0, 8));

		// 时间  
		byte[] bcdtime = new byte[6];
		System.arraycopy(data, 32, bcdtime, 0, 6);
		iotdata.setTime(HexTools.BytesBCDtoDate(bcdtime));
		//System.out.println(iotdata.getTime());

		iotdata.setOffset(deCodeInt(38));		//日雨量
		
		int[] rainvalues = new int[24];
		for(int i=0;i<24;i++) {
			rainvalues[i] = deCodeInt(i*2+40);	//从40字节开始
			iotdata.setRainvalues(null);
		}
		//上一小时雨量，如果是0点，取23点雨量
		Calendar date = Calendar.getInstance();
		date.add(Calendar.HOUR_OF_DAY, -1);		//1:05 获取0:00-1:00 的值——第一个值
		iotdata.setValue(rainvalues[date.get(Calendar.HOUR_OF_DAY)]);

		iotdata.setRainvalues(rainvalues);

		
		// 自编号-字符串？
		byte[] strid = new byte[16];
		System.arraycopy(data, 8, strid, 0, 16);

		// 设备类型-字符串
		byte[] strtype = new byte[8];
		System.arraycopy(data, 24, strtype, 0, 8);

		try {
			iotdata.setSid(new String(strid, "GB2312"));
			iotdata.setStype(new String(strtype, "GB2312").trim());
		} catch (Exception e) {
		}
	}


	//10分钟雨量计
	// 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F|
	// 传感器编号8字节           |自编号-16字节            |
	// 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F|
	//                        |型号8字节                |
	// 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F|
	// 年 月  日 00 00 00 |雨量数据144字节  应每10分钟1字节 |
	// 30 31 32 33 34....
	// --------------|
	void deCodeIotDataRain2() {
		// id
		System.out.println("10分钟雨量计："+HexTools.bytesToHex(receive));
		iotdata.setSuccess(true);
		
		iotdata.setIotid(HexTools.bytesToHexString(data, 0, 8));

		// 时间  
		byte[] bcdtime = new byte[6];
		System.arraycopy(data, 32, bcdtime, 0, 6);
		iotdata.setTime(HexTools.BytesBCDtoDate(bcdtime));
		//System.out.println(iotdata.getTime());

		iotdata.setOffset(deCodeInt(38));		//日雨量
		
		int[] rainvalues = new int[24];
		for(int i=0;i<24;i++) {
			int temp = 0;
			for(int j=i*6;j<(i+1)*6;j++) {
				temp += data[j+40]&0xFF;	//是否加 & 0xff
			}
			rainvalues[i] = temp;	//从40字节开始
		}
		
		//上一小时雨量，如果是0点，取23点雨量
		Calendar date = Calendar.getInstance();
		date.add(Calendar.HOUR_OF_DAY, -1);

		iotdata.setValue(rainvalues[date.get(Calendar.HOUR_OF_DAY)]);

		iotdata.setRainvalues(rainvalues);

		
		// 自编号-字符串？
		byte[] strid = new byte[16];
		System.arraycopy(data, 8, strid, 0, 16);

		// 设备类型-字符串
		byte[] strtype = new byte[8];
		System.arraycopy(data, 24, strtype, 0, 8);

		try {
			iotdata.setSid(new String(strid, "GB2312"));
			iotdata.setStype(new String(strtype, "GB2312").trim());
		} catch (Exception e) {
		}
	}

	
	int deCodeInt(int pos) {
		byte[] by = new byte[2];
		by[0] = by[1] = 0;
		System.arraycopy(data, pos, by, 0, 2);
		return HexTools.byte2ToInt(by);
	}

	int findHead() {
		byte[] temp = new byte[2];
		for (int i = 0; i < buff.length - 60; i++) {
			System.arraycopy(buff, i, temp, 0, 2);
			if (Arrays.equals(temp, head)) {
				return i;
			}
		}
		return -1; // 在剩下60字节也未发现
	}

	boolean checknum(byte[] buf) {

		int size = buf.length;
		byte check = buf[0];
		for (int i = 1; i < size - 1; i++) {
			check ^= buf[i];
		}
		//System.out.println(check == buf[size - 1]); 
		return (check == buf[size - 1]);
	}

	public void clearbuff() {
		for (int i = 0; i < buff.length; i++)
			buff[0] = 0;
	}

	public byte[] getBuff() {
		return buff;
	}

	public String toString() {
		return HexTools.bytesToHexString(buff,0,readnums);
	}


}
